package model

import (
	"database/sql"
	"errors"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"strings"
	"yunzhan/alert-server/internal/types"

	"github.com/zeromicro/go-zero/core/stores/builder"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"github.com/zeromicro/go-zero/core/stringx"
)

var (
	alertRuleFieldNames = builder.RawFieldNames(&types.AlertRule{})
	// `id`, `component`, `metric`, `operator`, `threshold`, `enabled`, `notification_id`, `notification_type`, `description`, `created_at`, `updated_at`
	alertRuleRows                = strings.Join(alertRuleFieldNames, ",")
	alertRuleRowsExpectAutoSet   = strings.Join(stringx.Remove(alertRuleFieldNames, "`id`", "`created_at`", "`updated_at`"), ",")
	alertRuleRowsWithPlaceHolder = strings.Join(stringx.Remove(alertRuleFieldNames, "`id`", "`created_at`", "`updated_at`"), "=?,") + "=?"
)

type (
	AlertRuleModel interface {
		Insert(data *types.AlertRule) (sql.Result, error)
		FindOne(id int64) (*types.AlertRule, error)
		FindAllEnabled() ([]types.AlertRule, error)
		Update(data *types.AlertRule) error
		Delete(id int64) error
	}

	defaultAlertRuleModel struct {
		conn  sqlx.SqlConn
		table string
	}
)

func NewAlertRuleModel(conn sqlx.SqlConn, table string) AlertRuleModel {
	return &defaultAlertRuleModel{
		conn:  conn,
		table: table,
	}
}

func (m *defaultAlertRuleModel) Insert(data *types.AlertRule) (sql.Result, error) {
	query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?, ?, ?)", m.table, alertRuleRowsExpectAutoSet)
	ret, err := m.conn.Exec(query, data.ComponentName, data.ComponentRole, data.Metric, data.Operator, data.Threshold, data.Enabled, data.NotificationConfig, data.Description)
	return ret, err
}

func (m *defaultAlertRuleModel) FindOne(id int64) (*types.AlertRule, error) {
	query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", alertRuleRows, m.table)
	logx.Infof("执行 SQL: %s, 参数: %d", query, id)
	var resp types.AlertRule
	err := m.conn.QueryRow(&resp, query, id)
	if err != nil {
		if errors.Is(err, sqlc.ErrNotFound) {
			errMsg := fmt.Sprintf("数据库中未找到相关数据，ID: %d", id)
			logx.Errorf(errMsg)
			return nil, fmt.Errorf("%w: %s", sqlc.ErrNotFound, errMsg)
		}
		errMsg := fmt.Sprintf("查询数据库中数据异常: %v", err)
		logx.Errorf(errMsg)
		return nil, fmt.Errorf("query error: %w", err)
	}
	return &resp, nil
}

func (m *defaultAlertRuleModel) FindAllEnabled() ([]types.AlertRule, error) {
	query := fmt.Sprintf("select %s from %s where `enabled` = 1", alertRuleRows, m.table)
	var rules []types.AlertRule
	err := m.conn.QueryRows(&rules, query)
	return rules, err
}

func (m *defaultAlertRuleModel) Update(data *types.AlertRule) error {
	query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, alertRuleRowsWithPlaceHolder)
	_, err := m.conn.Exec(query, data.ComponentName, data.ComponentRole, data.Metric, data.Operator, data.Threshold, data.Enabled, data.NotificationConfig, data.Description, data.ID)
	return err
}

func (m *defaultAlertRuleModel) Delete(id int64) error {
	query := fmt.Sprintf("delete from %s where `id` = ?", m.table)
	_, err := m.conn.Exec(query, id)
	return err
}
